<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="学科" prop="name">
            <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="年级" prop="level">
            <el-select v-model="ruleForm.level" placeholder="年级" @change="levelChange">
                <el-option :label="item.name" :value="item.value" v-for="item in levelStore.list" :key="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useLevelStore } from "@/stores/level"
import { subjectEdit, type SubjectEditParamsType  } from "@/api/education"
import { useRouter } from "vue-router"
import axios from 'axios'
//创建路由实例
const router = useRouter()

//pinia 年级的数据
const levelStore = useLevelStore()
//获取elFrom组件
const ruleFormRef = ref<FormInstance>()
//修改的表单数据
const ruleForm = ref<SubjectEditParamsType>({
    name: '',
    level: "",
    levelName: '',
    id: "",
})

//验证规则
const rules = ref<FormRules<SubjectEditParamsType>>({
    name: [
        { required: true, message: '请输入学科', trigger: 'blur' },
    ],
    level: [
        { required: true, message: '请选择年级', trigger: 'blur' },
    ],
})
//年级变化的事件
function levelChange(val:any){
    const level =levelStore.list.find(item=>item.value ==val)
    ruleForm.value.levelName=(level?.name as string)
}
//添加功能
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            subjectEdit(ruleForm.value).then(res=>{
                if(res.code ===1){
                    //提示
                    ElMessage({
                        message:'保存成功',
                        type:'success',
                        duration:1500,
                        onClose:()=>{
                            //跳转
                            router.push('/subject')
                        }
                    })
                }else{
                    ElMessage({
                        message:res.message,
                        type:'error'
                    })
                }
            })
        }
    })
}
//重置表单功能
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
// 页面加载时自动从路由参数获取id并赋值到ruleForm，实现编辑时id获取
onMounted(() => {
    // 尝试从路由参数获取id
    let routeId = router.currentRoute.value.query.id || router.currentRoute.value.params.id
    console.log('编辑页获取到的id:', routeId)
    if (Array.isArray(routeId)) {
        routeId = routeId.length > 0 ? routeId[0] : ''
    }
    // 自动转为数字类型
    if (typeof routeId === 'string' && routeId !== '') {
        routeId = Number(routeId)
    }
    if (typeof routeId === 'number' && !isNaN(routeId) && routeId > 0) {
        ruleForm.value.id = routeId
        // 调用学科详情接口并回显
        axios({
            url: `/api/admin/education/subject/select/${routeId}`,
            method: 'get'
        }).then(res => {
            console.log('学科详情接口返回:', res)
            if (res.data && res.data.code === 1 && res.data.response) {
                ruleForm.value.name = res.data.response.name
                ruleForm.value.level = res.data.response.level
                ruleForm.value.levelName = res.data.response.levelName
                ruleForm.value.id = res.data.response.id
            }
        })
    } else {
        console.warn('无效id，不请求详情接口')
    }
})
</script>